package com.android.jingweiapp.util;

import android.net.Uri;

import com.facebook.cache.common.CacheKey;
import com.facebook.cache.common.SimpleCacheKey;
import com.facebook.imagepipeline.cache.BitmapMemoryCacheKey;
import com.facebook.imagepipeline.cache.CacheKeyFactory;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.Postprocessor;

/**
 * Created by cuiwenrui-pc on 15/10/30.
 */
public class MyCacheKeyFactory implements CacheKeyFactory {

    private static MyCacheKeyFactory sInstance = null;

    protected MyCacheKeyFactory() {
    }

    public static synchronized MyCacheKeyFactory getInstance() {
        if (sInstance == null) {
            sInstance = new MyCacheKeyFactory();
        }
        return sInstance;
    }

    @Override
    public CacheKey getBitmapCacheKey(ImageRequest request) {
        return new BitmapMemoryCacheKey(
                getCacheKeySourceUri(request.getSourceUri()).toString(),
                request.getResizeOptions(),
                request.getAutoRotateEnabled(),
                request.getImageDecodeOptions(),
                null,
                null);
    }

    @Override
    public CacheKey getPostprocessedBitmapCacheKey(ImageRequest request) {
        final Postprocessor postprocessor = request.getPostprocessor();
        final CacheKey postprocessorCacheKey;
        final String postprocessorName;
        if (postprocessor != null) {
            postprocessorCacheKey = postprocessor.getPostprocessorCacheKey();
            postprocessorName = postprocessor.getClass().getName();
        } else {
            postprocessorCacheKey = null;
            postprocessorName = null;
        }
        return new BitmapMemoryCacheKey(
                getCacheKeySourceUri(request.getSourceUri()).toString(),
                request.getResizeOptions(),
                request.getAutoRotateEnabled(),
                request.getImageDecodeOptions(),
                postprocessorCacheKey,
                postprocessorName);
    }

    @Override
    public CacheKey getEncodedCacheKey(ImageRequest request) {
        return new SimpleCacheKey(getCacheKeySourceUri(request.getSourceUri()).toString());
    }

    @Override
    public Uri getCacheKeySourceUri(Uri sourceUri) {
        return Uri.parse(sourceUri.getEncodedPath());
    }
}
